//
//  ZQNetWorkManager.swift
//  新浪微博
//
//  Created by huami on 2019/11/19.
//  Copyright © 2019 huami. All rights reserved.
//

import AFNetworking
import UIKit
enum WBHTTPMethod {
    case GET
    case POST
}

class ZQNetWorkManager: AFHTTPSessionManager {
    static let shared: ZQNetWorkManager = {
        let instance = ZQNetWorkManager()
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        instance.responseSerializer.acceptableContentTypes?.insert("application/json")
        instance.responseSerializer.acceptableContentTypes?.insert("text/html")
        instance.responseSerializer.acceptableContentTypes?.insert("text/json")
        return instance
    }()

    /// 用户账户的懒加载属性
    lazy var userAccount = ZQUserAccount()

    var userLogin: Bool {
        return userAccount.access_token != nil
    }

    func tokenRequest(method: WBHTTPMethod = .GET, urlString: String, params: [String: AnyObject]?, completion: @escaping (_ json: AnyObject?, _ isSuccess: Bool) -> ()) {
        guard let token = userAccount.access_token else {
            // FIXME: 发送通知谁接收到谁来处理
            print("没有token,需要登录")
            completion(nil, false)
            return
        }

        var newParams = params
        if newParams == nil {
            newParams = [String: AnyObject]()
        }

        newParams!["access_token"] = token as AnyObject

        request(urlString: urlString, params: newParams, completion: completion)
    }

    func request(method: WBHTTPMethod = .GET, urlString: String, params: [String: AnyObject]?, completion: @escaping (_ json: AnyObject?, _ isSuccess: Bool) -> ()) {
        let success = { (_: URLSessionTask, json: Any?) -> () in
            completion(json as AnyObject?, true)
        }

        let failure = { (task: URLSessionTask?, error: Error) -> () in
            print("网络错误\(error)")

            // 针对 403 处理用户token过期
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("token过期了")

                // FIXME: 发送通知谁接收到谁来处理
            }
            completion(nil, false)
        }

        if method == .GET {
            get(urlString, parameters: params, progress: nil, success: success, failure: failure)
        } else {
            post(urlString, parameters: params, progress: nil, success: success, failure: failure)
        }
    }
}
